# 创建用户蓝图对象
from flask import Blueprint, render_template, request
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SubmitField, HiddenField
from wtforms.validators import DataRequired

from exts import db

grade_bp = Blueprint('grade', __name__, url_prefix='/grade')


class GradeModel(db.Model):
    """
    班级模型
    """
    __tablename__ = 't_grade'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 主键id
    name = db.Column(db.String(50), nullable=False)  # 班级名称
    remark = db.Column(db.Text)  # 备注


class Grade:
    def __init__(self, name, remark):
        self.name = name
        self.remark = remark


class GradeForm(FlaskForm):
    id = HiddenField()
    name = StringField("年级名称", render_kw={'placeholder': '请输入年级名称'}, validators=[DataRequired()])
    remark = TextAreaField("备注", render_kw={'placeholder': '请输入备注'})
    submit = SubmitField("登录")


@grade_bp.route('/list')
def index():
    gradeList = GradeModel.query.all()
    return render_template('grade/list.html', gradeList=gradeList)


@grade_bp.route('/add', methods=['GET', 'POST'])
def add():
    gradeForm = GradeForm()
    if request.method == 'GET':
        return render_template('grade/add.html', form=gradeForm)
    else:
        if gradeForm.validate():
            data = gradeForm.data
            gradeModel = GradeModel(name=data['name'], remark=data['remark'])
            db.session.add(gradeModel)
            db.session.commit()
            return index()


@grade_bp.route('/update', methods=['GET', 'POST'])
def update():
    gradeForm = GradeForm()
    if request.method == 'GET':
        id = request.args.get('id', type=int)
        grade = GradeModel.query.get(id)
        gradeForm.id.data = grade.id
        gradeForm.name.data = grade.name
        gradeForm.remark.data = grade.remark
        return render_template('grade/update.html', form=gradeForm)
    else:
        if gradeForm.validate():
            data = gradeForm.data
            print('data:', data)
            print(data['id'])
            grade = GradeModel.query.get(data['id'])
            grade.name = data['name']
            grade.remark = data['remark']
            db.session.commit()
            return index()


@grade_bp.route('/delete/<int:id>')
def delete(id):
    grade = GradeModel.query.get(id)
    db.session.delete(grade)
    db.session.commit()
    return index()
